package com.wechat.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.xiezc.annotation.Inject;
import org.xiezc.servlet.MyHttpServlet;

import com.wechat.model.HotSong;
import com.wechat.service.MusicService;
import com.wechat.util.ResponseUtils;

/**
 *
 * @author xiezc
 * @date 2016年7月17日 下午5:12:24
 */
@WebServlet("/music")
public class MusicServlet extends MyHttpServlet {

	private static final long serialVersionUID = 1L;
	@Inject
	private MusicService musicService;
	
	
	/**
	 * 下载music的servlet
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String songName = req.getParameter("songName");
		String songUrl = req.getSession().getServletContext().getRealPath("") + "WEB-INF/music/"
				+ URLDecoder.decode(songName, "utf-8");
		File file = new File(songUrl);
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		if (file.exists() && file.isFile()) {
			try {
				String fileName = file.getName().split("_")[0] + ".mp3";
				resp.reset();
				resp.setHeader("Content-Disposition",
						"attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
				resp.addHeader("Content-Length", "" + file.length());
				resp.setContentType("application/octet-stream");
				bis = new BufferedInputStream(new FileInputStream(file));
				bos = new BufferedOutputStream(resp.getOutputStream());
				byte[] b = new byte[1024];
				int num = 0;
				while ((num = bis.read(b)) > 0) {
					bos.write(b, 0, num);
				}
				bos.flush();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				bis.close();
				bos.close();
				resp.flushBuffer();
			}
		}
	}
	
	/**
	 * 翻页获得一页的歌曲
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String pageNo= req.getParameter("pageNo");
		String pageSize=req.getParameter("pageSize");
		String sname=req.getParameter("sname");
		if("".equals(sname)){
			sname=null;
		}
		List<HotSong> list= musicService.getMusics(sname, Integer.parseInt(pageNo), Integer.parseInt(pageSize));
		JSONArray jsonArray=new JSONArray(list);
		ResponseUtils.renderJson(resp, jsonArray.toString());
	}

	
	
	public MusicService getMusicService() {
		return musicService;
	}

	public void setMusicService(MusicService musicService) {
		this.musicService = musicService;
	}

}
